# !/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
@作者 杨阳
@时间 2018-06-21
@说明 处理用户相关的请求
@注意事项
"""
import json
import os

from flask import Blueprint, request, jsonify, send_from_directory
from flask_login import current_user

from model.SystemModel import TUserModel
from settings import IMPORT_USER_EXCEL_PATH, DOWNLOAD_IMPORT_USER_TEMPLATE_URL
from util import LogUtil
from util.FileUtil import allowed_update_file
from util.JsonUtil import classToDict, JsonEncoder
from util.SessionUtil import Mast_be_login_decorator
from util.StrUtil import get_uuid

user = Blueprint('user', __name__, url_prefix='/user')


@user.route("/grid/", methods=["POST"])
@Mast_be_login_decorator
def user_grid():
    """
    查询用户表格
    :return: json 字符串
    """
    current_page = request.form.get("current_page")
    group_id = request.form.get("group_id")
    search_name = request.form.get("search_name")
    search_sex = request.form.get("search_sex")
    search_start_data = request.form.get("search_start_data")
    search_end_data = request.form.get("search_end_data")

    return TUserModel.get_user_grid(current_page, group_id, search_name, search_sex, search_start_data, search_end_data)


@user.route("/delete/<id>", methods=["DELETE"])
@Mast_be_login_decorator
def delete(id):
    """
    删除用户
    :return:
    """
    LogUtil.info("用户id:{}".format(id))
    return TUserModel.delete_user(id)


@user.route("/import/", methods=["POST"])
@Mast_be_login_decorator
def excel():
    """
    通过excel文件导入用户
    :return:
    """
    if 'file' not in request.files:
        LogUtil.info("没有找到需要上传的文件!!!!!")
        return jsonify({'success': False, 'msg': '没有找到要上传的文件!'})

    # 获取要上传的文件
    file = request.files['file']

    bool = allowed_update_file(file.filename, "xlsx,xls")
    if not bool:
        return jsonify({'success': False, 'msg': '请选择excel文件上传!'})

    if not os.path.exists(IMPORT_USER_EXCEL_PATH):
        # 如果上传路径不存在，则创建路径
        os.makedirs(IMPORT_USER_EXCEL_PATH)

    try:
        # 获得文件的后缀名
        file_name_ext = file.filename[file.filename.rfind("."):]
        newFileName = str(get_uuid()) + file_name_ext

        LogUtil.info("新的文件名：{}".format(newFileName))

        file.save(os.path.join(IMPORT_USER_EXCEL_PATH, newFileName))

        return TUserModel.import_user(IMPORT_USER_EXCEL_PATH + "/" + newFileName)

    except Exception as e:
        LogUtil.info('上传文件异常!{}'.format(e))
        return jsonify({'success': False, 'msg': '上传文件异常!{}'.format(e)})


@user.route("/downtemplate/")
@Mast_be_login_decorator
def download_import_user_template():
    """
    下载导入用户模板
    :return:
    """
    dirpath = os.path.join(user.root_path, DOWNLOAD_IMPORT_USER_TEMPLATE_URL)
    LogUtil.info("dirpath:{}".format(dirpath))
    return send_from_directory(dirpath, "导入用户-模板.xlsx", as_attachment=True)


@user.route("/getresources/", methods=["GET"])
@Mast_be_login_decorator
def get_user_resources():
    """
    获得用户权限
    :return:
    """
    return TUserModel.get_user_resources(current_user.id)


@user.route("/exportexcel/", methods=["GET"])
@Mast_be_login_decorator
def export_excel():
    """
    导出excel
    :return:
    """
    file_name = TUserModel.export_user_excel()
    dirpath = os.path.join(user.root_path, IMPORT_USER_EXCEL_PATH)
    return send_from_directory(dirpath, file_name, as_attachment=True)


@user.route("/currentuser/", methods=["GET"])
@Mast_be_login_decorator
def get_current_user():
    """
    获得发前登录用户
    :return:
    """
    result = {"success": True, "current_user": classToDict(current_user)}
    return json.dumps(result, cls=JsonEncoder)


@user.route("/get/<id>", methods=["GET"])
@Mast_be_login_decorator
def get_user(id):
    """
    根据用户id获得用户
    :param id:      用户id
    :return:        json
    """
    user = TUserModel.get_user_byId(id)
    result = {"success": True, "user": classToDict(user)}
    return json.dumps(result, cls=JsonEncoder)


@user.route("/save/", methods=["POST"])
@Mast_be_login_decorator
def save_user():
    """
    增加或修改用户
    :return:
    """
    id = request.form.get("id")
    code = request.form.get("code")
    regname = request.form.get("regname")
    name = request.form.get("name")
    sex = request.form.get("sex")
    group_id = request.form.get("group_id")
    certificate_type = request.form.get("certificate_type")
    certificate = request.form.get("certificate")
    email = request.form.get("email")
    phone = request.form.get("phone")
    comment = request.form.get("comment")

    if id and id != "":
        return TUserModel.update_user(id, name, code, sex, certificate_type, certificate, phone, email, comment)
    else:
        return TUserModel.add_user(regname, name, code, sex, group_id, certificate_type,
                                   certificate, phone, email, comment)
